package com.letoken.platform.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.letoken.platform.pub.annotation.auth.Permission;
import com.letoken.platform.pub.annotation.pub.Trim;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.repo.admin.dao.AdminFundConfigMapper;
import com.letoken.platform.repo.admin.po.AdminFundConfig;
import com.letoken.platform.repo.admin.req.user.CapPledgeMiningIncomeRecordPageReq;
import com.letoken.platform.repo.admin.req.user.CapPledgeMiningRecordPageReq;
import com.letoken.platform.repo.app.dao.AppFundDetailMapper;
import com.letoken.platform.repo.app.dao.AppFundInfoMapper;
import com.letoken.platform.repo.app.po.AppFundInfo;
import com.letoken.platform.repo.app.req.user.IdReq;
import com.letoken.platform.repo.app.req.user.TypeReq;
import com.letoken.platform.repo.utlis.PageDataUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/cap/pledge_mining")
public class CapPledgeMiningController {

    @Resource
    private AdminFundConfigMapper mapper;

    @Resource
    private AppFundInfoMapper appFundInfoMapper;

    @Resource
    private AppFundDetailMapper appFundDetailMapper;

    @Permission(uri = "/cap/pledge_mining/config/list", qx = "/cap/pledge_mining/config/list")
    @Trim
    @PostMapping("/config/list")
    public ApiResponse list(@RequestBody TypeReq type) {

        QueryWrapper<AdminFundConfig> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(type.getTitle())) {
            queryWrapper.eq("title", type.getTitle());
        }
        queryWrapper.orderByDesc("create_time");
        return ApiResponse.create(mapper.selectList(queryWrapper));
    }

    @Permission(uri = "/cap/pledge_mining/config/dict", qx = "/cap/pledge_mining/config/dict")
    @Trim
    @GetMapping("/config/dict")
    public ApiResponse dict() {
        QueryWrapper<AdminFundConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "title");
        return ApiResponse.create(mapper.selectList(queryWrapper));
    }


    @Permission(uri = "/cap/pledge_mining/config/add", qx = "/cap/pledge_mining/config/add")
    @Trim
    @PostMapping("/config/add")
    public ApiResponse add(@RequestBody AdminFundConfig adminFundConfig) {
        BigDecimal rate = adminFundConfig.getMonthlyPercentage().divide(new BigDecimal(100)).divide(new BigDecimal("30"), 6, RoundingMode.DOWN);
        adminFundConfig.setRate(rate);
        adminFundConfig.setCreateTime(LocalDateTime.now());
        mapper.insert(adminFundConfig);
        return ApiResponse.create();
    }

    @Permission(uri = "/cap/pledge_mining/config/update", qx = "/cap/pledge_mining/config/update")
    @Trim
    @PostMapping("/config/update")
    public ApiResponse update(@RequestBody AdminFundConfig adminFundConfig) {

        if (null != adminFundConfig.getMonthlyPercentage()) {
            BigDecimal rate = adminFundConfig.getMonthlyPercentage().divide(new BigDecimal(100)).divide(new BigDecimal("30"), 6, RoundingMode.DOWN);
            adminFundConfig.setRate(rate);
        }

        mapper.updateById(adminFundConfig);
        return ApiResponse.create();
    }

    @Permission(uri = "/cap/pledge_mining/config/del", qx = "/cap/pledge_mining/config/del")
    @Trim
    @PostMapping("/config/del")
    public ApiResponse del(@RequestBody IdReq idReq) {
        mapper.deleteById(idReq.getId());
        return ApiResponse.create();
    }

    @Permission(uri = "/cap/pledge_mining/quantity/statistics", qx = "/cap/pledge_mining/quantity/statistics")
    @Trim
    @PostMapping("/quantity/statistics")
    public ApiResponse statistics() {

        Map<String, String> result = new HashMap<>();

        LocalDateTime now = LocalDateTime.now();

        result.put("all", appFundInfoMapper.sum(null, null, null).toString());
        result.put("allEffectivity", appFundInfoMapper.sum(1, null, now).toString());

        result.put("allMinitype", appFundInfoMapper.sum(null, 1, null).toString());
        result.put("allMinitypeEffectivity", appFundInfoMapper.sum(1, 1, now).toString());

        result.put("allMediumSized", appFundInfoMapper.sum(null, 2, null).toString());
        result.put("allMediumSizedEffectivity", appFundInfoMapper.sum(1, 2, now).toString());

        result.put("allLarge", appFundInfoMapper.sum(null, 3, null).toString());
        result.put("allLargeEffectivity", appFundInfoMapper.sum(1, 3, now).toString());
        return ApiResponse.create(result);
    }


    @Permission(uri = "/cap/pledge_mining/record/page", qx = "/cap/pledge_mining/record/page")
    @Trim
    @PostMapping("/record/page")
    public ApiResponse recordPage(@RequestBody CapPledgeMiningRecordPageReq req) {
        Page<AppFundInfo> page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        appFundInfoMapper.page(page, req);
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(r -> {
                if (null != r.getType() && r.getType() == 1 && null != r.getExpirationTime() && LocalDateTime.now().isAfter(r.getExpirationTime())) {
                    r.setType(3);
                }
            });
        }
        return ApiResponse.create(PageDataUtil.getPageData(page));
    }


    @Permission(uri = "/cap/pledge_mining/income/statistics", qx = "/cap/pledge_mining/income/statistics")
    @Trim
    @PostMapping("/income/statistics")
    public ApiResponse incomeStatistics() {

        Map<String, String> result = new HashMap<>();

        LocalDate yesterdayDate = LocalDate.now().minusDays(1);
        BigDecimal yesterday = appFundDetailMapper.sum(LocalDateTime.of(yesterdayDate, LocalTime.MIN), LocalDateTime.of(yesterdayDate, LocalTime.MAX));
        result.put("yesterday", BigDecimal.ZERO.compareTo(yesterday) == 0 ? "0" : yesterday.toString());

        LocalDate today = LocalDate.now();
        BigDecimal now = appFundDetailMapper.sum(LocalDateTime.of(today, LocalTime.MIN), LocalDateTime.of(today, LocalTime.MAX));
        result.put("today", BigDecimal.ZERO.compareTo(now) == 0 ? "0" : now.toString());

        LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        BigDecimal currentMonth = appFundDetailMapper.sum(LocalDateTime.of(firstDayOfMonth, LocalTime.MIN), LocalDateTime.of(lastDayOfMonth, LocalTime.MAX));
        result.put("currentMonth", BigDecimal.ZERO.compareTo(currentMonth) == 0 ? "0" : currentMonth.toString());

        BigDecimal sum = appFundDetailMapper.sum(null, null);
        result.put("all", BigDecimal.ZERO.compareTo(sum) == 0 ? "0" : sum.toString());
        return ApiResponse.create(result);
    }


    @Permission(uri = "/cap/pledge_mining/income/page", qx = "/cap/pledge_mining/income/page")
    @Trim
    @PostMapping("/income/page")
    public ApiResponse recordPage(@RequestBody CapPledgeMiningIncomeRecordPageReq req) {
        Page page = new Page<>(req.getPageReq().getPage(), req.getPageReq().getSize());
        appFundDetailMapper.page(page, req);
        return ApiResponse.create(PageDataUtil.getPageData(page));
    }


}
